<template>
  <div>
    <van-button type="primary" @click="openCamera">打开摄像头</van-button>
    <van-button type="info" @click="capture">捕获画面</van-button>
    <van-button type="warning" @click="uploadPhoto">上传照片</van-button>
    <van-button type="success" @click="submitAllPhotos">提交</van-button>
    <video ref="video" autoplay playsinline></video>
    <img v-if="capturedPhoto" :src="capturedPhoto" alt="捕获的照片" />
    <img v-if="uploadedPhoto" :src="uploadedPhoto" alt="上传的照片" />
  </div>
</template>

<script setup>
import { ref } from 'vue';
import http from '../../../../../http';

// 创建响应式数据
const mediaStream = ref(null);
const capturedPhoto = ref(null);
const uploadedPhoto = ref(null);
const isCameraOpen = ref(false);

// 打开摄像头函数
const openCamera = async () => {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ video: true });
    mediaStream.value = stream;
    const video = document.querySelector('video');
    video.srcObject = stream;
    video.play();
    isCameraOpen.value = true;
  } catch (error) {
    console.error('打开摄像头出错：', error);
  }
};

// 捕获画面函数
const capture = () => {
  const video = document.querySelector('video');
  const canvas = document.createElement('canvas');
  canvas.width = video.videoWidth;
  canvas.height = video.videoHeight;
  const ctx = canvas.getContext('2d');
  ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
  capturedPhoto.value = canvas.toDataURL('image/png');
  closeCamera();
};

// 上传照片函数
const uploadPhoto = () => {
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = 'image/*';
  input.onchange = (e) => {
    const file = e.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => {
        uploadedPhoto.value = reader.result;
      };
      reader.readAsDataURL(file);
    }
  };
  input.click();
};

// 提交所有照片函数
const submitAllPhotos = () => {
  const dataToSend = {};
  if (capturedPhoto.value) {
    dataToSend.img1 = capturedPhoto.value.split(',')[1]; // 提取Base64编码部分（去除前面的data:image/png;base64, 等头部信息）
  }
  if (uploadedPhoto.value) {
    dataToSend.img2 = uploadedPhoto.value.split(',')[1];
  }
  http.post('/user/face/', dataToSend).then((res) => {
    console.log(res.data);
  }).catch((error) => {
    console.error('提交照片出错：', error);
  });
};

// 关闭摄像头函数
const closeCamera = () => {
  if (mediaStream.value) {
    mediaStream.value.getTracks().forEach(track => track.stop());
    mediaStream.value = null;
    isCameraOpen.value = false;
  }
  const video = document.querySelector('video');
  video.style.display = 'none';
};

// 在组件卸载前调用关闭摄像头函数
import { onBeforeUnmount } from 'vue';
onBeforeUnmount(() => {
  closeCamera();
});
</script>

<style>
video {
  width: 300px;
  height: 200px;
  margin-bottom: 10px;
}
img {
  width: 300px;
  height: 200px;
  margin-bottom: 10px;
}
</style>